package be.nabu.vfs.provider;

import java.util.HashMap;
import java.util.Map;
import java.util.ServiceLoader;

import be.nabu.vfs.provider.api.StoreFactory;

public class SPISchemeResolver implements SchemeResolver {
	
	private static ServiceLoader<StoreFactory> serviceLoader = ServiceLoader.load(StoreFactory.class);

	private Map<String, StoreFactory> resolvedLoaders = new HashMap<String, StoreFactory>();

	@Override
	public StoreFactory getStoreFactory(String scheme) {
		if (!resolvedLoaders.containsKey(scheme)) {
			StoreFactory correctFactory = null;
			for (StoreFactory factory : serviceLoader) {
				if (factory.getSchemes().contains(scheme)) {
					correctFactory = factory;
					break;
				}
			}
			resolvedLoaders.put(scheme, correctFactory);
		}
		return resolvedLoaders.get(scheme);
	}
	
}
